package com.touchalachs.core;

import java.util.LinkedList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.touchalachs.core.updateThread.UpdateNDrawThread;
import com.touchalachs.core.updateThread.UpdateThread;

public abstract class GameView extends SurfaceView implements SurfaceHolder.Callback {

	private final UpdateThread updateThread;
	private final LinkedList<Drawable> drawables;
	private final LinkedList<Updatable> updatables;
	private final LinkedList<Touchable> touchables;
	
	
	public GameView(Context context, Point screnSize) {
		super(context);
		drawables = new LinkedList<Drawable>();
		updatables = new LinkedList<Updatable>();
		touchables = new LinkedList<Touchable>();
		initUI(screnSize);
		initObjects(screnSize);
		getHolder().addCallback(this);
//		updateThread = new UpdateNBufferedDrawThread(this, screnSize);
		updateThread = new UpdateNDrawThread(this);
	}

	abstract protected void initObjects(Point screnSize);
	abstract protected void initUI(Point screnSize);
	
	protected void addUpdatable(Updatable u) {
		updatables.add(u);
	}
	
	protected void addDrawable(Drawable d) {
		drawables.add(d);
	}

	protected void addTouchable(Touchable t) {
		touchables.add(t);
	}
	
	@Override
	final public void draw(Canvas canvas) {
		super.draw(canvas);
		canvas.drawColor(Color.BLACK);
		for (Drawable d:drawables){
			d.draw(canvas);
		}
	}

	public void update(float deltaSec) {
		for (Updatable u:updatables){
			u.update(deltaSec);
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		for (Touchable t:touchables){
			if (t.onTouchEvent(event)){
				return true;
			}
		}
		return  super.onTouchEvent(event) || true;
	}
	
	
	
	// --------------------

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
		updateThread.setRunning(false);
		while (retry) {
			try {
				updateThread.join();
				retry = false;
			} catch (InterruptedException e) {
				android.util.Log.i("", e.toString());
			}
		}
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		updateThread.setRunning(true);
		updateThread.start();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
	}

}
